package com.yunxi.rocketmq.consumer;

import com.aliyun.openservices.ons.api.*;
import com.yunxi.core.base.Constant;
import com.yunxi.model.eai.EaiLog;
import com.yunxi.rocketmq.config.RocketMQConfig;
import com.yunxi.service.eai.EaiLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;

/**
 * Created by Administrator on 2019/6/17.
 */
@Component
public class OtdPlanMonthConsumer implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private RocketMQConfig rocketMQConfig;
    @Value("${aliyun.rocketMQ.month.plan.topic}")
    private String topic;
    @Value("${aliyun.rocketMQ.month.otd.tag}")
    private String tag;
    @Value("${aliyun.rocketMQ.otd.month.consumerGroup}")
    private String group;
    @Autowired
    @Qualifier("eaiLogServiceImpl")
    EaiLogService eaiLogService;
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent)  {
        Properties properties = rocketMQConfig.getProperties();
        properties.put(PropertyKeyConst.GROUP_ID,group);
        // 集群订阅方式设置（不设置的情况下，默认为集群订阅方式）
        properties.put(PropertyKeyConst.MessageModel, PropertyValueConst.CLUSTERING);

        Consumer consumer = ONSFactory.createConsumer(properties);
        consumer.subscribe(topic, tag, new MessageListener() {
            @Override
            public Action consume(Message message, ConsumeContext context) {
                System.out.println(tag+ " Receive: " + new String(message.getBody()));
                try {
                    String monthPlan = new String(message.getBody(), "utf-8");
                    EaiLog eaiLog=new EaiLog();
                    eaiLog.setType(1);
                    eaiLog.setPmsEaiContent(monthPlan);
                    eaiLog.setRequestSendTime(new Date());
                    eaiLog.setFlowDesc("PMS系统发送月计划给SAP系统");
                    eaiLog.setSourceSystem(Constant.PMS);
                    eaiLog.setServiceName(Constant.SAP_MONTH_PLAN);
                    eaiLog.setDisposeStatus(0);
                    eaiLog.setCreateDate(new Date());
                    eaiLogService.saveOrUpdate(eaiLog);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

                return Action.CommitMessage;
            }
        });

        consumer.start();
        System.out.println("消费者启动===========");
    }
}
